package com.dingpeikeji.quickdeer.modules.rentproduct.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductInvoiceService;

/**
 * 发票
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/rentproduct/invoice")
public class RentproductInvoiceController {

	@Autowired
	private RentproductInvoiceService rentproductInvoiceService;
	/**
	 * 整车已支付订单列表
	 */
	@RequiresPermissions("rentproduct:invoice:view")
	@RequestMapping("orders")
	public String orders(TOrders orders,Model model,HttpServletRequest request, HttpServletResponse response){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(StringUtils.isEmpty(orders.getPayDateQueryStart()) && 
				StringUtils.isEmpty(orders.getPayDateQueryEnd())){ // 采用默认时间范围
			Calendar calendar = Calendar.getInstance();
			Date end = calendar.getTime();
			calendar.add(Calendar.MONTH, -1);
			Date start = calendar.getTime();
			orders.setPayDateQueryStart(sdf.format(start));
			orders.setPayDateQueryEnd(sdf.format(end));
		}
		model.addAttribute("page", rentproductInvoiceService.findOrderWithRentproductPage(new Page<TOrders>(request, response)	, orders));
		model.addAttribute("orders", orders);
		return "modules/rentproduct/invoiceOrders";
	}
	
	/**
	 * 开发票
	 */
	@RequiresPermissions("rentproduct:invoice:edit")
	@RequestMapping("make")
	public String make(TOrders orders,RedirectAttributes redirectAttributes){
		if(rentproductInvoiceService.updateCheck(orders)){
			redirectAttributes.addFlashAttribute("message", "已开发票");
		} else {
			redirectAttributes.addFlashAttribute("message", "发票未开成功");
		}
		return "redirect:"+Global.getAdminPath()+"/rentproduct/invoice/orders?repage";
	}
}
